package validation;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by v on 17-5-7.
 */
public class Validation {
    public static boolean LoginValidation(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session=req.getSession();

        //若无cookie直接
        if(req.getCookies()==null){
            return false;
        }

        Map<String,Cookie> map=ReadCookies(req.getCookies());

        //获取用户及动态密码相对应的Cookie
        Cookie user=map.get("user");
        Cookie pwd=map.get("pwd");
        if(user==null||pwd==null){
            return false;
        }

        String validation=(String) session.getAttribute(user.getValue());
        if(validation==null){
            return false;
        }

        if(!validation.equals(req.getRemoteAddr()+pwd.getValue())){
            return false;
        }

        return true;
    }

    /**
     *
     * @param cookies cookie数组
     * @return 根据cookie数组转化的map
     */
    public static Map<String,Cookie> ReadCookies(Cookie[] cookies){
        Map<String,Cookie> map=new HashMap<>();

        for(int i=0;i<cookies.length;i++){
            map.put(cookies[i].getName(),cookies[i]);
        }

        return map;
    }
}
